package com.laivi.basic.model.file.reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.laivi.basic.common.listener.CallBack;
import com.laivi.basic.module.log.Log;
import com.laivi.basic.module.log.Logs;
import com.laivi.basic.util.DataUtil;

public class TxtReader {
	private final static Log log=Logs.getLog(TxtReader.class);
	
	private File file;
	private String coding="utf-8";			//读取文件编码格式
	private boolean isRead=true;            //是否继续往后读数据
	
	public TxtReader(String path){
		this(new File(path));
	}
	
	public TxtReader(File file) {
		this.file = file;
	}
	
	public List<String> read(final int start,final int end){
		final List<String> lines=new ArrayList<String>();
		this.read(new CallBack(){

			@Override
			public void execute(Object... params) throws Exception {
				int i=Integer.parseInt(String.valueOf(params[0]));
				String line=String.valueOf(params[1]);
				if(i>=start && (end==0||start>end||i<=end)){
					lines.add(line);
				}
				if(start<end && end!=0 && i>end){
					isRead=false;
				}
			}
		});
		return lines;
	}
	
	public void read(CallBack back){
		BufferedReader br=null;
		try{
			if(DataUtil.isEmpty(this.coding)){
				br=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			}else{
				br=new BufferedReader(new InputStreamReader(new FileInputStream(file),this.coding));
			}
			String line=null;
			int i=0;
			while(isRead &&(line=br.readLine())!=null){
				back.execute(i++,line);
			}
		}catch(Exception e){
			log.error("error:"+e.getMessage());
		}finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					log.error("error:"+e.getMessage());
				}
			}
		}
	}

	public void setCoding(String coding) {
		this.coding = coding;
	}

	public void setRead(boolean isRead) {
		this.isRead = isRead;
	}
}
